import os
from typing import Optional

BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))


def is_managed_upload(path: Optional[str]) -> bool:
    """
    判断路径是否为项目可管理的上传文件路径（uploads 目录下）
    """
    if not path:
        return False
    p = str(path).strip()
    if p.lower().startswith('/uploads/') or p.lower().startswith('uploads/'):
        # 过滤默认占位图等静态资源
        return True
    return False


def to_fs_path(web_path: str) -> str:
    """
    将形如 /uploads/xxx 的站点路径转换为文件系统路径
    """
    rel = web_path.lstrip('/').replace('/', os.sep)
    return os.path.join(BASE_DIR, rel)


def safe_delete_file(path: Optional[str]) -> None:
    """
    安全删除文件：仅删除 uploads 目录下存在的文件，忽略异常
    """
    if not is_managed_upload(path):
        return
    fs_path = to_fs_path(str(path))
    try:
        if os.path.exists(fs_path) and os.path.isfile(fs_path):
            os.remove(fs_path)
    except Exception:
        # 忽略删除异常，避免影响主流程
        pass


def safe_replace_file(obj: object, field_name: str, new_path: Optional[str]) -> None:
    """
    在对象字段更新为新文件路径时，自动删除旧文件（仅限 uploads 目录）
    """
    old_path = getattr(obj, field_name, None)
    if old_path and new_path and str(old_path) != str(new_path):
        safe_delete_file(old_path)
    setattr(obj, field_name, new_path)